﻿using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using Microsoft.Extensions.Options;
using System;
using System.Collections.Generic;
using System.Text;
using TianShu.Data;
using TianShu.Domain;
using TianShu.Modularity;
using TianShu.Security;
using TianShu.SqlSugarCore.Configs;
using TianShu.SqlSugarCore.DependencyInjection;
using TianShu.SqlSugarCore.SqlSugarFactory;
using TianShu.SqlSugarCore.SqlSugarFactory.uow;
using TianShu.SqlSugarCore.Uow;
using TianShu.Threading;
using TianShu.Uow;

namespace TianShu.SqlSugarCore
{
    [DependsOn(
        typeof(TianShuDomainModule),
        typeof(TianShuSecurityModule),
        typeof(AbpUnitOfWorkModule),
        typeof(AbpDataModule)
        )]
    public class TianShuSqlSugarCoreModule : AbpModule
    {
        public override void ConfigureServices(ServiceConfigurationContext context)
        {
            context.Services.AddScoped<ISqlSugarClientFactory, DefaultSqlSugarClientFactory>();


            context.Services.TryAddTransient(typeof(IUowSqlSugarFactory), typeof(UnitOfWorkSugarClientProvider));
        }

        public override void OnApplicationInitialization(ApplicationInitializationContext context)
        {
            var genTable = context.ServiceProvider.GetService<IOptions<SugarAutoGeneratorTableOptions>>().Value;
            if (genTable.IsCreateDatabase())
            {
                var SugarClient = context.ServiceProvider.GetService<ISqlSugarClientFactory>();
                var client = SugarClient.CreateClient();
                client.DbMaintenance.CreateDatabase();

                foreach (var item in genTable.GetEntityTypes())
                {
                    try
                    {

                        client.CodeFirst.InitTables(item);
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine($"实体类：{item.Name} 生成错误,{ex}");
                    }
                }
            }
        }
    }
}
